package user_manager

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"github.com/gin-gonic/gin"
)

// todo: 修改用户数据 (密码需要 sha256)
func SetUserData(c *gin.Context) {
	if _, err := util.AdminFilter(c); err != nil {
		return
	}

	userID, err := util.PostFormInt(c, "id")
	if err != nil {
		return
	}

	password := c.PostForm("password")
	nickname := c.PostForm("nickname")
	phone := c.PostForm("phone")

	updateValue := make(map[string]interface{})
	if password != "" {
		updateValue["password"] = util.Sha256(password)
	}
	if nickname != "" {
		updateValue["nickname"] = nickname
	}
	if phone != "" {
		updateValue["phone"] = phone
	}

	if db.DB.Model(&models.User{}).
		Where("`id` = ?", userID).
		Updates(updateValue).RowsAffected == 0 {
		util.FailedResponse(c, 10002, "更改信息失败")
		return
	}

	util.SuccessResponse(c)
}

func SetAvatarUrl(c *gin.Context) {
	if _, err := util.AdminFilter(c); err != nil {
		return
	}

	userID, err := util.PostFormInt(c, "id")
	if err != nil {
		return
	}

	avatarUrl := c.PostForm("avatar_url")

	if err := db.DB.Model(&models.User{}).Where("`id` = ?", userID).
		Update("avatar", avatarUrl).Error; err != nil {
		util.FailedResponse(c, 10001, "此用户ID不存在")
		return
	}

	util.SuccessResponse(c)
}
